package cn.psvmc.cxzapi.config.mybatisplus.service.impl;

import cn.psvmc.cxzapi.config.mybatisplus.mapper.MyBaseMapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.ibatis.logging.Log;
import org.apache.ibatis.logging.LogFactory;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.List;

/**
 * @date 通用接口抽象实现类
 * @param <T>
 */
public abstract class AbstractService<M extends MyBaseMapper<T>, T> extends ServiceImpl<M,T> {

    protected Log log = LogFactory.getLog(this.getClass());


    private static final int BATCH_SIZE = 1000;


    /**
     * 全量插入,等价于insert
     *
     * @param list 集合列表
     * @param batchSize 集合列表的长度
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public boolean fastSaveBatch(List<T> list, int batchSize) {
        if(CollectionUtils.isEmpty(list)) {
            return true;
        }

        if(list.size() <= batchSize) {
            return retBool(getBaseMapper().insertBatchSomeColumn(list));
        }

        for (int fromIdx = 0 , endIdx = batchSize ; ; fromIdx += batchSize, endIdx += batchSize) {
            if(endIdx > list.size()) {
                endIdx = list.size();
            }
            getBaseMapper().insertBatchSomeColumn(list.subList(fromIdx, endIdx));
            if(endIdx == list.size()) {
                return true;
            }
        }
    }

    /**
     * 全量插入,等价于insert
     *
     * @param list 集合列表
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public boolean fastSaveBatch(List<T> list) {
        return fastSaveBatch(list, BATCH_SIZE);
    }

    /**
     * 全量更新，不忽略null字段，等价于update
     * 解决mybatis-plus会自动忽略null字段不更新
     *
     * @param t 实体类
     * @return
     */
    public boolean updateAllColById(T t) {
        return retBool(getBaseMapper().alwaysUpdateSomeColumnById(t));
    }

}
